// pages/profile/profile.js

import { updateAvatar, updateNickName } from '../../api/profile.js'
const Storage = require('../../utils/storage')

Page({
  data: {
    userInfo: {}
  },

  onLoad() {
    // 获取本地存储的用户信息
    const userInfo = Storage.getUserInfo()
    if (userInfo) {
      this.setData({ userInfo })
    }
  },

  onShow() {
    // 设置tabBar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 'profile'
      })
    }
  },

  // 处理选择头像
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    this.setData({
      'userInfo.avatarUrl': avatarUrl
    })
    this.updateUserInfo()
  },

  // 处理输入昵称
  async onInputNickname(e) {
    const nickName = e.detail.value
    this.setData({
      'userInfo.nickName': nickName
    })
    await this.updateUserInfo()
  },

  // 更新本地存储的用户信息
  async updateUserInfo() {
    Storage.setUserInfo(this.data.userInfo)
    if(this.data.userInfo.avatarUrl){
      await updateAvatar(this.data.userInfo.avatarUrl);
    }
    if(this.data.userInfo.nickName){
      await updateNickName(this.data.userInfo.nickName);
    }
  },

  // 页面跳转
  navigateTo(e) {
    const path = e.currentTarget.dataset.path
    wx.navigateTo({
      url: path,
      fail: () => {
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
  }
})